package com.itqiqi.api.sink;

import com.itqiqi.api.pojo.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class SourceTest3_JDBC {

    public static void main(String[] args) throws Exception {

        // 获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 使数据有顺序
        env.setParallelism(1);

        DataStreamSource<String> dataStream = env.readTextFile("input/sensor.txt");

        // 转换成SensorReading类型
        SingleOutputStreamOperator<SensorReading> inputMap = dataStream.map((MapFunction<String, SensorReading>) s -> {
            String[] fields = s.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 连接mysql
        inputMap.addSink(new RichSinkFunction<SensorReading>() {

            Connection connection;
            PreparedStatement updateStat;
            PreparedStatement insetStat;

            @Override
            public void open(Configuration parameters) throws Exception {
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false", "root", "0902");
                updateStat = connection.prepareStatement("update test.sensor_temp set temp = ? where id = ?");
                insetStat = connection.prepareStatement("insert into test.sensor_temp (id ,temp) values (?, ?)");
            }

            @Override
            public void close() throws Exception {
                connection.close();
                updateStat.close();
                insetStat.close();
            }

            @Override
            public void invoke(SensorReading value, Context context) throws Exception {
                updateStat.setDouble(1, value.getTemperature());
                updateStat.setString(2, value.getId());
                updateStat.execute();

                if (updateStat.getUpdateCount() == 0) {
                    insetStat.setString(1, value.getId());
                    insetStat.setDouble(2, value.getTemperature());
                    insetStat.execute();
                }
            }
        });


        env.execute();

    }
}
